import cv2
import numpy as np
import PickBlue
from skimage.measure import label

# 通过找到发票上红色的印章来计算整张发票的相对大小
def calScale(image):
    print("基于红色印章计算相对大小")
    img = image.copy()
    img_origin = img.copy()
    cv2.imshow("origin", img)
    h, w, _ = img.shape
    for i in range(0, h):
        for j in range(0, w):
            B = float(img[i][j][0])
            G = float(img[i][j][1])
            R = float(img[i][j][2])
            if R/max(G + R + B, 1) > 0.38 and R + B + G > 150:
                img[i][j] = [0, 0, 0]
            else:
                img[i][j] = [255, 255, 255]
    cv2.imshow("pickRed", img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # img = PickBlue.erode_demo(img, 2)
    # cv2.imshow("erode_img", img)
    # img = PickBlue.dilate_demo(img, 20)
    # cv2.imshow("dilate_img", img)

    # 计算不同的连通域，将面积最大的几块取出来，认为是要取出的几块
    # print("计算不同的连通域，将面积最大的几块取出来，认为是要取出的几块")
    labeled_img, num = label(img, connectivity=1, background=1, return_num=True)
    all_set = set(())
    for i in range(0, h):
        for j in range(0, w):
            all_set.add(labeled_img[i][j])
    # print(all_set)
    # print(labeled_img)
    # print(num)

    label_sum = [0] * num
    label_num = [0] * num
    for i in range(num):
        label_num[i] = i + 1
    # print(label_num)

    for i in range(0, h):
        for j in range(0, w):
            if img[i][j] == 0:
                label_sum[labeled_img[i][j]-1] += 1
    # print(label_sum)
    max_sum = 0
    max_label = 0
    for i in range(num):
        if label_sum[i] > max_sum:
            max_sum = label_sum[i]
            max_label = i + 1
    # print(max_label)
    single_labeled_img = labeled_img.copy()
    for i in range(h):
        for j in range(w):
            if labeled_img[i][j] == max_label:
                single_labeled_img[i][j] = 0
            else:
                single_labeled_img[i][j] = 255
    # cv2.imshow("single_img", single_labeled_img)
    # print(single_labeled_img)
    min_area = h*w
    min_rect = [0, 0, 0, 0]
    min_rotate = 0
    print("寻找最佳旋转角度:")
    for j in range(-10, 10, 1):
        r_img = PickBlue.rotate_img(single_labeled_img, j)
        rect, area_percent = PickBlue.get_rect(r_img)
        area = (rect[3]-rect[2]) * (rect[1]-rect[0])
        if area < min_area:
            min_area = area
            min_rect = rect
            min_rotate = j
        print("-", end='')
    print("\n图像切割选择角度:", min_rotate)
    print(min_rect, rect[3]-rect[2])
    cv2.rectangle(img_origin, (min_rect[0], min_rect[2]), (min_rect[1], min_rect[3]), (0, 0, 255), 1)
    cv2.imshow('scale_red', img_origin)
    # print(new_single_labeled_img)
    return rect[3] - rect[2]


if __name__ == "__main__":
    image = cv2.imread("receipt_img/ticket4.jpg")
    print(calScale(image))
    cv2.waitKey(0)
    cv2.destroyAllWindows()
